<template>
	<uni-file-picker
		v-model="imageValue"
		:file-mediatype="fileMediatype"
		:mode="mode"
		:limit="limit"
		:source-type="sourceType"
		:disable-preview="disablePreview"
		@progress="progress"
		@success="success"
		@fail="fail"
		@select="select"
		ref="uploadRef"
	>
		<slot />
	</uni-file-picker>
</template>

<script setup>
import { ref } from 'vue';
import { uploadFile } from '@/hook/useWechatFile.js';

const emits = defineEmits(['on-success', 'update:modelValue']);

const props = defineProps({
	modelValue: { type: [Object, Array, String], default: '' }, // Object [{ "name":"file.txt", "extname":"txt", "url":"https://xxxx" }]
	fileMediatype: { type: String, default: 'image' }, // image/video/all
	limit: { type: [String, Number], default: 1 },
	mode: { type: String, default: 'grid' }, //list/grid
	sourceType: { type: Array, default: () => ['album'] }, // ['album', 'camera']
	disablePreview: { type: Boolean, default: false },
	scope: { type: String, default: 'other' }, // chat knowledge other
	useOriginalFileName: { type: Boolean, default: false }, // 是否使用源文件名
});

const uploadRef = ref(null);
const imageValue = ref(props.modelValue || []);

const progress = e => {
	console.log('progress', e);
};

const success = e => {
	console.log('success', e);
};

const fail = e => {
	console.log('fail', e);
};

const select = async e => {
	let { tempFiles } = e;

  if (tempFiles.length == 0) {
    uni.showToast({ title: '请选择文件' })
    return;
  }

  if (props.limit == 1) {
    let res = await uploadFile({
      file: tempFiles[0],
      props: {
        key: `${uni.getStorageSync('manufacturerId')}/${props.scope}/`
      },
			useOriginalFileName: props.useOriginalFileName,
    });

		props.disablePreview && uploadRef.value.clearFiles();

		emits('on-success', res)
		emits('update:modelValue', res.filepath)
  }
  else {

  }
};
</script>

<style lang="scss">
.base-uploader {
}
</style>
